package com.skin.configuration.shiro;

import com.skin.admin.entity.*;
import com.skin.admin.manager.PermManager;
import com.skin.admin.manager.RoleManager;
import com.skin.admin.manager.UsersManager;
import com.skin.admin.serviceImpl.UsersServiceImpl;
import com.skin.tools.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2018/7/20 0020.
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UsersManager usersManager;

    @Autowired
    private RoleManager roleManager;

    @Autowired
    private PermManager permManager;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Users userInfo  = (Users)principals.getPrimaryPrincipal();
//        for(Roles role:userInfo.getRoleList()){
//            authorizationInfo.addRole(role.getRole());
//            for(SysPermission p:role.getPermissions()){
//                authorizationInfo.addStringPermission(p.getPermission());
//            }
//        }
        //set类型配置
        List<Userrole> userroleList=  roleManager.findUserroleBy("userid",userInfo.getId().toString());
        if(!userroleList.isEmpty()){
            Set<String> rolesSet =new HashSet<>();
            Set<String> permissionsSet =new HashSet<>();
            for(Userrole u :userroleList){
                if(u.getRoleid()!=null){
                    String id =u.getRoleid().toString();
                    List<Roles> rolesList=roleManager.findListBy("id",id);
                    for(Roles r :rolesList){
                        rolesSet.add(r.getName());//角色添加
                    }

                    List<Permissions> permissionsList=permManager.findPermByRole(id);
                    for(Permissions p:permissionsList){
                        permissionsSet.add(p.getDesc());  //权限查找
                        System.out.println("当前用户的权限"+p.getDesc());
                    }
                }
            }
            //角色添加
            authorizationInfo.setRoles(rolesSet);
            //权限添加
            authorizationInfo.setStringPermissions(permissionsSet);
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        System.out.println("token.getCredentials():"+new String((char[])token.getCredentials()));

        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        Users userInfo = usersManager.findBy("name",username);
        System.out.println("----->>userInfo="+userInfo.getName());
        if(userInfo == null){
            return null;
        }
        if (!userInfo.getPassword().equals(new String((char[]) token.getCredentials()))) {
            throw new AuthenticationException();
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo, //用户名
                userInfo.getPassword(), //密码
//                ByteSource.Util.bytes(userInfo.getSalt()),//salt=username+salt
                getName()  //realm name
        );

        return authenticationInfo;
    }
}
